{% extends "base.html" %}

{% block content %}
<div class="row justify-content-center">
    <div class="col-lg-8">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2>
                <i class="bi bi-pencil-square me-2"></i>写邮件
            </h2>
            <a href="{{ url_for('main.inbox') }}" class="btn btn-outline-secondary">
                <i class="bi bi-arrow-left me-1"></i>返回收件箱
            </a>
        </div>

        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">新邮件</h5>
            </div>
            <div class="card-body">
                <form id="composeForm">
                    <!-- 收件人 -->
                    <div class="mb-3">
                        <label for="recipient" class="form-label">
                            <i class="bi bi-person me-1"></i>收件人 <span class="text-danger">*</span>
                        </label>
                        <div class="input-group">
                            <input type="text" class="form-control" id="recipient" name="recipient" 
                                   placeholder="输入用户名或邮箱地址" required autocomplete="off">
                            <button class="btn btn-outline-secondary" type="button" id="searchUserBtn" 
                                    title="搜索用户">
                                <i class="bi bi-search"></i>
                            </button>
                        </div>
                        <div class="form-text">
                            可以输入用户名或邮箱地址，系统会自动匹配
                        </div>
                        <!-- 用户搜索结果 -->
                        <div id="userSearchResults" class="mt-2" style="display: none;">
                            <div class="card">
                                <div class="card-body p-2">
                                    <div id="userList"></div>
                                </div>
                            </div>
                        </div>
                        <!-- 收件人验证状态 -->
                        <div id="recipientValidation" class="mt-2"></div>
                    </div>

                    <!-- 主题 -->
                    <div class="mb-3">
                        <label for="subject" class="form-label">
                            <i class="bi bi-tag me-1"></i>主题 <span class="text-danger">*</span>
                        </label>
                        <input type="text" class="form-control" id="subject" name="subject" 
                               placeholder="请输入邮件主题" required maxlength="200">
                        <div class="form-text">
                            <span id="subjectCount">0</span>/200 字符
                        </div>
                    </div>

                    <!-- 内容 -->
                    <div class="mb-4">
                        <label for="content" class="form-label">
                            <i class="bi bi-file-text me-1"></i>内容 <span class="text-danger">*</span>
                        </label>
                        <textarea class="form-control" id="content" name="content" rows="12" 
                                  placeholder="请输入邮件内容..." required maxlength="5000"></textarea>
                        <div class="form-text">
                            <span id="contentCount">0</span>/5000 字符
                        </div>
                    </div>

                    <!-- 操作按钮 -->
                    <div class="d-flex justify-content-between">
                        <div>
                            <button type="button" class="btn btn-outline-secondary" onclick="saveDraft()">
                                <i class="bi bi-save me-1"></i>保存草稿
                            </button>
                            <button type="button" class="btn btn-outline-warning" onclick="clearForm()">
                                <i class="bi bi-arrow-clockwise me-1"></i>清空
                            </button>
                        </div>
                        <div>
                            <button type="button" class="btn btn-outline-secondary me-2" onclick="previewEmail()">
                                <i class="bi bi-eye me-1"></i>预览
                            </button>
                            <button type="submit" class="btn btn-primary" id="sendBtn">
                                <i class="bi bi-send me-1"></i>发送
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- 邮件预览模态框 -->
<div class="modal fade" id="previewModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="bi bi-eye me-2"></i>邮件预览
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="email-preview">
                    <div class="mb-3">
                        <strong>收件人：</strong>
                        <span id="previewRecipient"></span>
                    </div>
                    <div class="mb-3">
                        <strong>主题：</strong>
                        <span id="previewSubject"></span>
                    </div>
                    <div class="mb-3">
                        <strong>内容：</strong>
                        <div id="previewContent" class="border rounded p-3 bg-light" style="white-space: pre-wrap;"></div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="sendEmailFromPreview()">
                    <i class="bi bi-send me-1"></i>发送邮件
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
let searchTimeout;
let recipientValidated = false;

document.addEventListener('DOMContentLoaded', function() {
    const recipientInput = document.getElementById('recipient');
    const subjectInput = document.getElementById('subject');
    const contentTextarea = document.getElementById('content');
    const composeForm = document.getElementById('composeForm');
    const searchUserBtn = document.getElementById('searchUserBtn');
    
    // 收件人输入事件
    recipientInput.addEventListener('input', function() {
        const value = this.value.trim();
        recipientValidated = false;
        
        // 清除之前的搜索结果
        document.getElementById('userSearchResults').style.display = 'none';
        document.getElementById('recipientValidation').innerHTML = '';
        
        if (value.length >= 2) {
            // 防抖搜索
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(() => {
                searchUsers(value);
            }, 500);
        }
    });
    
    // 搜索按钮点击事件
    searchUserBtn.addEventListener('click', function() {
        const value = recipientInput.value.trim();
        if (value) {
            searchUsers(value);
        }
    });
    
    // 主题字符计数
    subjectInput.addEventListener('input', function() {
        document.getElementById('subjectCount').textContent = this.value.length;
    });
    
    // 内容字符计数
    contentTextarea.addEventListener('input', function() {
        document.getElementById('contentCount').textContent = this.value.length;
    });
    
    // 表单提交
    composeForm.addEventListener('submit', function(e) {
        e.preventDefault();
        sendEmail();
    });
    
    // 自动保存草稿（每30秒）
    setInterval(autoSaveDraft, 30000);
    
    // 页面离开前提醒
    window.addEventListener('beforeunload', function(e) {
        const hasContent = recipientInput.value.trim() || 
                          subjectInput.value.trim() || 
                          contentTextarea.value.trim();
        
        if (hasContent) {
            e.preventDefault();
            e.returnValue = '您有未保存的邮件内容，确定要离开吗？';
        }
    });
});

// 搜索用户
async function searchUsers(query) {
    try {
        const response = await apiRequest(`/api/users/search?q=${encodeURIComponent(query)}`);
        
        if (response.success && response.users.length > 0) {
            displayUserSearchResults(response.users);
        } else {
            // 验证输入的收件人
            validateRecipient(query);
        }
    } catch (error) {
        console.error('搜索用户失败:', error);
        validateRecipient(query);
    }
}

// 显示用户搜索结果
function displayUserSearchResults(users) {
    const userList = document.getElementById('userList');
    const resultsDiv = document.getElementById('userSearchResults');
    
    userList.innerHTML = '';
    
    users.forEach(user => {
        const userItem = document.createElement('div');
        userItem.className = 'user-item p-2 border-bottom cursor-pointer';
        userItem.style.cursor = 'pointer';
        userItem.innerHTML = `
            <div class="d-flex align-items-center">
                <i class="bi bi-person-circle me-2"></i>
                <div>
                    <div class="fw-bold">${user.username}</div>
                    <small class="text-muted">${user.email}</small>
                </div>
            </div>
        `;
        
        userItem.addEventListener('click', function() {
            selectUser(user);
        });
        
        userList.appendChild(userItem);
    });
    
    resultsDiv.style.display = 'block';
}

// 选择用户
function selectUser(user) {
    const recipientInput = document.getElementById('recipient');
    recipientInput.value = user.username;
    
    document.getElementById('userSearchResults').style.display = 'none';
    
    // 显示验证成功状态
    const validationDiv = document.getElementById('recipientValidation');
    validationDiv.innerHTML = `
        <div class="alert alert-success py-2">
            <i class="bi bi-check-circle me-1"></i>
            收件人：${user.username} (${user.email})
        </div>
    `;
    
    recipientValidated = true;
}

// 验证收件人
async function validateRecipient(recipient) {
    try {
        const response = await apiRequest('/auth/check-user', {
            method: 'POST',
            body: JSON.stringify({ identifier: recipient })
        });
        
        const validationDiv = document.getElementById('recipientValidation');
        
        if (response.exists) {
            validationDiv.innerHTML = `
                <div class="alert alert-success py-2">
                    <i class="bi bi-check-circle me-1"></i>
                    收件人验证成功
                </div>
            `;
            recipientValidated = true;
        } else {
            validationDiv.innerHTML = `
                <div class="alert alert-danger py-2">
                    <i class="bi bi-x-circle me-1"></i>
                    用户不存在，请检查用户名或邮箱地址
                </div>
            `;
            recipientValidated = false;
        }
    } catch (error) {
        console.error('验证收件人失败:', error);
        recipientValidated = false;
    }
}

// 发送邮件
async function sendEmail() {
    const recipient = document.getElementById('recipient').value.trim();
    const subject = document.getElementById('subject').value.trim();
    const content = document.getElementById('content').value.trim();
    
    // 表单验证
    if (!recipient || !subject || !content) {
        showAlert('请填写所有必填字段', 'warning');
        return;
    }
    
    if (!recipientValidated) {
        showAlert('请先验证收件人', 'warning');
        return;
    }
    
    const sendBtn = document.getElementById('sendBtn');
    const originalText = sendBtn.innerHTML;
    
    try {
        // 显示发送中状态
        sendBtn.disabled = true;
        sendBtn.innerHTML = '<i class="bi bi-hourglass-split me-1"></i>发送中...';
        
        const response = await apiRequest('/api/emails/send', {
            method: 'POST',
            body: JSON.stringify({
                recipient: recipient,
                subject: subject,
                content: content
            })
        });
        
        if (response.success) {
            showAlert('邮件发送成功！', 'success');
            
            // 清空表单（发送成功后自动清空，不需要确认）
            clearFormAfterSend();
            
            // 跳转到已发送页面
            setTimeout(() => {
                window.location.href = '/sent';
            }, 1500);
        }
    } catch (error) {
        showAlert(error.message, 'danger');
    } finally {
        // 恢复按钮状态
        sendBtn.disabled = false;
        sendBtn.innerHTML = originalText;
    }
}

// 从预览发送邮件
function sendEmailFromPreview() {
    // 关闭模态框
    const modal = bootstrap.Modal.getInstance(document.getElementById('previewModal'));
    modal.hide();
    
    // 发送邮件
    sendEmail();
}

// 预览邮件
function previewEmail() {
    const recipient = document.getElementById('recipient').value.trim();
    const subject = document.getElementById('subject').value.trim();
    const content = document.getElementById('content').value.trim();
    
    if (!recipient || !subject || !content) {
        showAlert('请填写所有字段后再预览', 'warning');
        return;
    }
    
    // 填充预览内容
    document.getElementById('previewRecipient').textContent = recipient;
    document.getElementById('previewSubject').textContent = subject;
    document.getElementById('previewContent').textContent = content;
    
    // 显示模态框
    const modal = new bootstrap.Modal(document.getElementById('previewModal'));
    modal.show();
}

// 清空表单
// 清空表单（用户手动点击清空按钮时需要确认）
function clearForm() {
    if (confirm('确定要清空所有内容吗？')) {
        document.getElementById('composeForm').reset();
        document.getElementById('subjectCount').textContent = '0';
        document.getElementById('contentCount').textContent = '0';
        document.getElementById('userSearchResults').style.display = 'none';
        document.getElementById('recipientValidation').innerHTML = '';
        recipientValidated = false;
    }
}

// 发送成功后自动清空表单（不需要确认）
function clearFormAfterSend() {
    document.getElementById('composeForm').reset();
    document.getElementById('subjectCount').textContent = '0';
    document.getElementById('contentCount').textContent = '0';
    document.getElementById('userSearchResults').style.display = 'none';
    document.getElementById('recipientValidation').innerHTML = '';
    recipientValidated = false;
}

// 保存草稿
function saveDraft() {
    const recipient = document.getElementById('recipient').value.trim();
    const subject = document.getElementById('subject').value.trim();
    const content = document.getElementById('content').value.trim();
    
    if (!recipient && !subject && !content) {
        showAlert('没有内容需要保存', 'info');
        return;
    }
    
    // 保存到本地存储
    const draft = {
        recipient: recipient,
        subject: subject,
        content: content,
        timestamp: new Date().toISOString()
    };
    
    localStorage.setItem('emailDraft', JSON.stringify(draft));
    showAlert('草稿已保存到本地', 'success');
}

// 自动保存草稿
function autoSaveDraft() {
    const recipient = document.getElementById('recipient').value.trim();
    const subject = document.getElementById('subject').value.trim();
    const content = document.getElementById('content').value.trim();
    
    if (recipient || subject || content) {
        const draft = {
            recipient: recipient,
            subject: subject,
            content: content,
            timestamp: new Date().toISOString()
        };
        
        localStorage.setItem('emailDraft', JSON.stringify(draft));
    }
}

// 加载草稿
function loadDraft() {
    const draft = localStorage.getItem('emailDraft');
    if (draft) {
        try {
            const draftData = JSON.parse(draft);
            
            if (confirm('发现本地保存的草稿，是否加载？')) {
                document.getElementById('recipient').value = draftData.recipient || '';
                document.getElementById('subject').value = draftData.subject || '';
                document.getElementById('content').value = draftData.content || '';
                
                // 更新字符计数
                document.getElementById('subjectCount').textContent = draftData.subject ? draftData.subject.length : 0;
                document.getElementById('contentCount').textContent = draftData.content ? draftData.content.length : 0;
                
                // 如果有收件人，验证一下
                if (draftData.recipient) {
                    validateRecipient(draftData.recipient);
                }
                
                showAlert('草稿已加载', 'success');
            }
        } catch (error) {
            console.error('加载草稿失败:', error);
        }
    }
}

// 页面加载完成后尝试加载草稿
window.addEventListener('load', function() {
    setTimeout(loadDraft, 1000);
});
</script>
{% endblock %}